module.exports = (sequelize, DataTypes) => {
  const Admin = sequelize.define('Admin', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      validate: {
        len: [3, 50],
        notEmpty: true
      }
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
        notEmpty: true
      }
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'password_hash',
      validate: {
        notEmpty: true,
        len: [6, 255]
      }
    },
    real_name: {
      type: DataTypes.STRING(50),
      allowNull: true,
      validate: {
        len: [1, 50]
      }
    },
    role: {
      type: DataTypes.ENUM('admin', 'super_admin'),
      defaultValue: 'admin'
    },
    avatar: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'avatar_url'
    },
    permissions: {
      type: DataTypes.JSON,
      allowNull: true,
      defaultValue: [],
      comment: '权限列表'
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive'),
      defaultValue: 'active',
      field: 'is_active'
    },
    last_login_at: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
    tableName: 'admins',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        unique: true,
        fields: ['username']
      },
      {
        unique: true,
        fields: ['email']
      },
      {
        fields: ['role']
      },
      {
        fields: ['is_active']
      }
    ]
  });

  // 实例方法
  Admin.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    delete values.password; // 不返回密码字段
    return values;
  };

  // 实例方法：检查权限
  Admin.prototype.hasPermission = function(permission) {
    if (this.role === 'super_admin') {
      return true; // 超级管理员拥有所有权限
    }
    return this.permissions && this.permissions.includes(permission);
  };

  // 实例方法：添加权限
  Admin.prototype.addPermission = function(permission) {
    if (!this.permissions) {
      this.permissions = [];
    }
    if (!this.permissions.includes(permission)) {
      this.permissions.push(permission);
    }
    return this.save();
  };

  // 实例方法：移除权限
  Admin.prototype.removePermission = function(permission) {
    if (this.permissions) {
      this.permissions = this.permissions.filter(p => p !== permission);
    }
    return this.save();
  };

  return Admin;
}; 